module cxl_mem_controller #(
  parameter NODE_ID = 0,
  parameter TOTAL_MEM = 256 // 内存池总容量(GB)
)(
  input  wire         cxl_clk,
  input  wire         cxl_rst_n,
  
  // CXL.cache协议接口
  input  cxl_cache_req_t  cache_req,
  output cxl_cache_rsp_t  cache_rsp,
  
  // CXL.mem协议接口
  output cxl_mem_req_t    mem_req,
  input  cxl_mem_rsp_t    mem_rsp,
  
  // 本地内存接口
  output wire [63:0]  local_addr,
  inout  wire [511:0] local_data
);

  // 地址转换表
  reg [63:0] addr_map[TOTAL_MEM/2:0]; 
  
  // 一致性协议状态机
  typedef enum {
    IDLE, SNOOP, MEM_WRITE, WAIT_ACK
  } state_t;
  state_t current_state;

  always @(posedge cxl_clk) begin
    if (!cxl_rst_n) begin
      current_state <= IDLE;
    end else case(current_state)
      IDLE: 
        if (cache_req.valid) begin
          if (addr_map[cache_req.addr[63:40]] == NODE_ID) begin
            // 本地命中
            cache_rsp.data = local_mem.read(cache_req.addr);
            current_state <= IDLE;
          end else begin
            // 触发远端访问
            mem_req.addr = {addr_map[cache_req.addr[63:40]], cache_req.addr[39:0]};
            current_state <= SNOOP;
          end
        end
        
      SNOOP:
        if (mem_rsp.valid) begin
          local_data <= mem_rsp.data;
          current_state <= MEM_WRITE;
        end
        
      MEM_WRITE:
        if (local_mem.write_ready) begin
          current_state <= WAIT_ACK;
        end
      
      WAIT_ACK:
        if (cache_req.ack) begin
          current_state <= IDLE;
        end
    endcase
  end

endmodule